package com.eonmind.knowledge.config;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.aliyun.bailian20231229.Client;
import com.eonmind.common.contract.exception.BusinessException;
import com.eonmind.common.contract.oss.config.OssProperties;
import com.eonmind.knowledge.properties.BailianProperties;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: AKang
 * @Description:
 * @CreateTime: 2025-05-29
 */
@Configuration
public class BailianAutoConfigure {


    @Resource
    private OssProperties ossProperties;

    @Resource
    private BailianProperties bailianProperties;

    /**
     * 百炼调用时需要配置DashScope API,对dashScopeApi强依赖
     * @return
     */
    @Value("${spring.ai.dashscope.api-key}")
    private String apiKey;

    @Bean
    public DashScopeApi dashScopeApi() {
        return new DashScopeApi(apiKey);
    }

    /**
     * 实例化百炼客户端
     * @return
     * @throws Exception
     */
    @Bean
    public Client client() throws Exception {
        return createClient();
    }

    public com.aliyun.bailian20231229.Client createClient(){
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential)
                .setAccessKeyId(ossProperties.getAccessKeyId())
                .setAccessKeySecret(ossProperties.getAccessKeySecret());

        config.endpoint = bailianProperties.getEndpoint();
        try {
            return new com.aliyun.bailian20231229.Client(config);
        } catch (Exception e) {
            throw new BusinessException("百炼知识库客户端初始化失败！");
        }
    }

}
